import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_oldman_health/api/auth_service.dart';
import 'package:flutter_oldman_health/pages/register_page.dart';
import 'package:flutter_oldman_health/pages/setting/reset_psw_page.dart';
import 'package:flutter_oldman_health/utils/utils.dart';
import 'package:flutter_oldman_health/widget/common_container.dart';

class LoginPage extends StatefulWidget {
  @override
  LoginPageState createState() {
    return LoginPageState();
  }
}

class LoginPageState extends State<LoginPage> {
  var textEditPhone = '';
  String textEditPsw = '';
  // TextEditingController _controllerPhone;

  bool isLoading = false;

  void getUserId() {
    Utils.getStrSharePreferences("phone").then((value) {
      if (null != value && value.length > 0) {
        setState(() {
          textEditPhone = value;
        });
      }
    });
    Utils.getStrSharePreferences("token").then((value) {
      if (null != value && value.length > 0) {
        setState(() {
          textEditPsw = value;
        });
      }
    });
  }

  @override
  void initState() {
    super.initState();
    //bool _savePsw = false;
    getUserId();

    // TextEditingController _controllerPsw = TextEditingController();
    //_controllerPhone = TextEditingController(text: textEditPsw);
    // _controllerPhone.addListener(() {
    //   setState(() {
    //     textEditPhone = _controllerPhone.text;
    //   });
    // });
    // _controllerPsw.addListener(() {
    //   setState(() {
    //     textEditPsw = _controllerPsw.text;
    //   });
    // });
  }

  @override
  Widget build(BuildContext context) {
    Color endColor = Color(int.parse("0xffFF3FB9AF"));
    Color startColor = Color(int.parse("0xffFF4DDB9D"));
    return Scaffold(
        resizeToAvoidBottomInset: true,
        body: Container(
            decoration: BoxDecoration(
                gradient: LinearGradient(
                    colors: [startColor, endColor],
                    begin: AlignmentDirectional.topStart,
                    end: AlignmentDirectional.bottomEnd)),
            child: FractionallySizedBox(
                heightFactor: 1,
                //,
                child: Stack(children: [
                  Container(
                      child: SingleChildScrollView(
                          padding: EdgeInsets.fromLTRB(16, 100, 16, 0),
                          child: Column(children: [
                            Image.asset(
                              "images/logo.png",
                              height: 30,
                              fit: BoxFit.fitHeight,
                            ),
                            Text(
                              "欢迎登录",
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 30,
                              ),
                            ),
                            CommonContainer(
                                Row(children: [
                                  Text("手机号:  ",
                                      style: TextStyle(
                                          fontSize: 18, color: Colors.white)),
                                  Expanded(
                                      flex: 1,
                                      child: TextField(
                                          controller: TextEditingController
                                              .fromValue(TextEditingValue(
                                                  text:
                                                      '${this.textEditPhone == null ? "" : this.textEditPhone}',
                                                  //判断keyword是否为空
                                                  // 保持光标在最后
                                                  selection: TextSelection
                                                      .fromPosition(TextPosition(
                                                          affinity: TextAffinity
                                                              .downstream,
                                                          offset:
                                                              '${this.textEditPhone}'
                                                                  .length)))),
                                          keyboardType: TextInputType.number,
                                          onChanged: (v) {
                                            textEditPhone = v;
                                            print(
                                                "textEditPhone $textEditPhone");
                                          },
                                          inputFormatters: [
                                            LengthLimitingTextInputFormatter(
                                                11),
                                            FilteringTextInputFormatter
                                                .digitsOnly
                                          ],
                                          autofocus: false,
                                          style: TextStyle(
                                              fontSize: 18,
                                              color: Colors.black87,
                                              fontWeight: FontWeight.w300),
                                          // obscureText: true,
                                          decoration:
                                              getInputDecoration("请输入手机号")))
                                ]),
                                margin: EdgeInsets.only(top: 30),
                                padding: EdgeInsets.fromLTRB(16, 6, 16, 6),
                                colorBg: Colors.transparent),
                            CommonContainer(
                                Row(children: [
                                  Text("密码:  ",
                                      style: TextStyle(
                                          fontSize: 18, color: Colors.white)),
                                  Expanded(
                                      flex: 1,
                                      child: TextField(
                                          // controller: _controllerPhone,
                                          obscureText: true,
                                          maxLines: 1,
                                          autofocus: false,
                                          onChanged: (v) {
                                            textEditPsw = v;
                                          },
                                          inputFormatters: [
                                            LengthLimitingTextInputFormatter(12)
                                          ],
                                          style: TextStyle(
                                              fontSize: 18,
                                              color: Colors.black87,
                                              fontWeight: FontWeight.w300),
                                          // obscureText: true,
                                          decoration:
                                              getInputDecoration("请输入密码")))
                                ]),
                                margin: EdgeInsets.only(top: 20),
                                padding: EdgeInsets.fromLTRB(16, 6, 16, 6),
                                colorBg: Colors.transparent),
                            CommonContainer(
                                GestureDetector(
                                    behavior: HitTestBehavior.translucent,
                                    onTap: () {
                                      if (isLoading) return;
                                      print(textEditPhone.length.toString());
                                      if (textEditPhone.isEmpty ||
                                          !Utils.phoneStr(textEditPhone)||
                                          textEditPhone.length != 11) {
                                        EasyLoading.showInfo("手机号码输入有误");
                                      } else if (textEditPsw.isEmpty) {
                                        EasyLoading.showInfo("请输入密码");
                                      } else {
                                        setState(() {
                                          isLoading = true;
                                        });
                                        _login(textEditPhone, textEditPsw);
                                      }
                                    },
                                    child: FractionallySizedBox(
                                        widthFactor: 1,
                                        child: Text("登录",
                                            textAlign: TextAlign.center,
                                            style: TextStyle(
                                                fontWeight: FontWeight.bold,
                                                fontSize: 19,
                                                color: Color(0xff41BAB0))))),
                                margin: EdgeInsets.only(top: 30),
                                padding: EdgeInsets.all(16),
                                colorBg: Colors.white,
                                colorBorder: Color(0xFFEEEEEE),
                                radiusCircular: 58),
                            CommonContainer(
                                GestureDetector(
                                    behavior: HitTestBehavior.translucent,
                                    onTap: () {
                                      if (isLoading) return;

                                      Navigator.push(
                                          context,
                                          MaterialPageRoute(
                                              builder: (context) =>
                                                  RegisterPage()));
                                    },
                                    child: FractionallySizedBox(
                                        widthFactor: 1,
                                        child: Text("注册",
                                            textAlign: TextAlign.center,
                                            style: TextStyle(
                                                fontWeight: FontWeight.bold,
                                                fontSize: 19,
                                                color: Color(0xff41BAB0))))),
                                margin: EdgeInsets.only(top: 20),
                                padding: EdgeInsets.all(16),
                                colorBg: Colors.white,
                                colorBorder: Color(0xFFEEEEEE),
                                radiusCircular: 58),
                            // Container(
                            //     padding: EdgeInsets.fromLTRB(8, 8, 16, 10),
                            //     alignment: Alignment.centerLeft,
                            //     child: Row(children: [
                            //       Radio(
                            //           value: _savePsw,
                            //           onChanged: (check) {
                            //             setState(() {
                            //               _savePsw = check;
                            //             });
                            //           }),
                            //       GestureDetector(
                            //      behavior: HitTestBehavior.translucent,
                            //         onTap: () {
                            //           setState(() {
                            //             _savePsw = !_savePsw;
                            //           });
                            //         },
                            //         child: Text("记住密码",
                            //             style:
                            //                 TextStyle( fontSize: 17)),
                            //       )
                            //     ])),
                            Container(
                                padding: EdgeInsets.fromLTRB(8, 8, 16, 10),
                                alignment: Alignment.center,
                                child: GestureDetector(
                                  behavior: HitTestBehavior.translucent,
                                  onTap: () {
                                    if (isLoading) return;

                                    Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                            builder: (context) =>
                                                ResetPswPage()));
                                  },
                                  // child: Expanded(
                                  child: Text("忘记密码",
                                      style: TextStyle(
                                          color: Colors.white, fontSize: 17)),
                                  // flex: 1)
                                ))
                          ]))),
                  if (isLoading)
                    Align(
                        alignment: Alignment.center,
                        child: CommonContainer.loadingView(h: 50))
                ]))));
  }

  InputDecoration getInputDecoration(String hintText) {
    return InputDecoration(
        hintText: hintText,
        hintStyle: TextStyle(fontSize: 18),
        //InputBorder.none  OutlineInputBorder()
        border: InputBorder.none);
  }

  void _login(String phone, String password) async {
    AuthService.checkoutUserInfo(phone).then((value) {
      if (value != null) {
        if (value.msg == "用户不存在") {
          EasyLoading.showInfo('该手机号尚未注册');
          setState(() {
            isLoading = false;
          });
          return false;
        }
        if (value.data == 1) {
          EasyLoading.showInfo('该账号只能在老人机登录');
          setState(() {
            isLoading = false;
          });
          return false;
        }
      }

      AuthService.login2(context, phone, password, "登录成功", false).then((value) {
        setState(() {
          isLoading = false;
        });
      });
    });

    // Login login = Login(name: phone, random: randomInt.toString(), pass: pass1);
    // LoginModel value = await ApiClient().login(login);
    // print(("ApiClient login ： ${value.msg}"));
  }
}
